<template>
  <a-card class="content" :bordered="false">
    <div class="table-page-search-wrapper">
      <!-- 顶部搜索 -->
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="广告状态">
              <a-select placeholder="请选择广告状态" v-model="queryParam.status">
                <a-select-option :value="0">冻结</a-select-option>
                <a-select-option :value="1">激活</a-select-option>
                <a-select-option :value="2">全部</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span
              class="table-page-search-submitButtons"
              :style="advanced && { float: 'right', overflow: 'hidden' } || {} "
            >
              <a-button type="primary" @click="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 新建按钮 -->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="newBulid()">新建</a-button>
    </div>
    <!-- 主要内容表格 -->
    <a-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="merchantAdColumns"
      :dataSource="loadData"
      :pagination="pagination"
      :loading="loading"
      @change="pageChange"
      class="merlist"
    >
      <span slot="imgUrl" slot-scope="text">
        <img :src="text" width="40" />
      </span>

      <span slot="adType" slot-scope="text">
        <a-tag color="blue" v-if="text === 0">全部</a-tag>
        <a-tag color="blue" v-if="text === 1">轮播</a-tag>
        <a-tag color="blue" v-if="text === 2">分类精选</a-tag>
        <a-tag color="blue" v-if="text === 3">横幅</a-tag>
        <a-tag color="blue" v-if="text === 4">首页轮播下5分类按钮</a-tag>
        <a-tag color="blue" v-if="text === 5">首页横幅广告</a-tag>
      </span>
      <span slot="status" slot-scope="text">
        <a-tag color="blue" v-if="text === 1">激活</a-tag>
        <a-tag color="blue" v-if="text === 0">冻结</a-tag>
      </span>

      <span slot="action" slot-scope="text, record" class="clearfix">
        <a-button type="primary" class="flyray-btn" @click="adEdit(record)">修改</a-button>

        <a-button
          type="danger"
          class="table-danger flyray-btn"
          @click="delvisible=true; delData=record"
        >删除</a-button>
      </span>
    </a-table>
    <!-- 新建模态框 -->
    <a-modal :title="title" :width="951" :visible="visible" @ok="submit" @cancel="closeModal">
      <a-form :form="form" style="width: 60%">
        <a-form-item label="广告标题" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="[
              'title',
              { rules: [{ required: true, message: '请输入广告标题' }] },
            ]"
            placeholder="请输入广告标题"
          />
        </a-form-item>
        <a-form-item label="广告图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            listType="picture-card"
            class="avatar-uploader"
            :showUploadList="false"
            :action="uploadPhoto"
            :beforeUpload="beforeUpload"
            @change="imgUpload"
            v-decorator="[
          'imgUrl',
          {
            rules: [
              { required: true, message: '请上传广告图片' },
            ],
          },
        ]"
          >
            <img v-if="formData.imgUrl" :src="formData.imgUrl" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="广告类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            placeholder="请选择广告类型"
            v-decorator="[
          'adType',
          {
            rules: [
              { required: true, message: '请选择广告类型' },
            ],
          },
        ]"
            :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
          >
            <a-select-option :value="0">全部</a-select-option>
            <a-select-option :value="1">轮播</a-select-option>
            <a-select-option :value="2">分类精选</a-select-option>
            <a-select-option :value="3">横幅</a-select-option>
            <a-select-option :value="4">首页轮播下5分类按钮</a-select-option>
            <a-select-option :value="5">首页横幅</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="广告状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            placeholder="请选择广告状态"
            v-decorator="[
          'status',
          {
            rules: [
              { required: true, message: '请选择广告状态' },
            ],
          },
        ]"
            :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
          >
            <a-select-option :value="0">冻结</a-select-option>
            <a-select-option :value="1">激活</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="活动链接" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <div class="block">
            <el-cascader
              :options="activeOptions"
              :props="{ expandTrigger: 'hover' }"
              @change="cascderchange"
              v-model="formData.url"
            ></el-cascader>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 删除模态框 -->
    <a-modal title="提示" :width="500" :visible="delvisible" @ok="adDelete" @cancel="delvisible=false">
      <p>此操作将永久删除该广告{{delData.title}}, 是否继续?</p>
    </a-modal>
  </a-card>
</template>

<script>
import { getAdlist, deleteAdvertisement, editSubmit, buildSubmit, getCategoryTree } from '@/api/mall/merchantAd'
import { merchantAdColumns, statusMap } from '@/const/crud/mall/merchantAd.config'
import config from '@/config/appConfig'

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}

export default {
  name: 'TableList',
  data() {
    return {
      uploadPhoto: config.uploadPicturesUrl,
      merchantAdColumns,
      statusMap,
      queryParam: {
        // 查询参数
        adId: null,
        adType: null
      },
      parameter: {
        //列表参数
        pageNo: 1,
        pageSize: 10,
        status: undefined
      },
      pagination: {
        //页脚
        total: 0,
        pageSize: 10,
        showTotal: total => `共有 ${total} 条数`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '30', '40'],
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize)
      },
      labelCol: {
        //模态框label尺寸
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        //模态框尺寸
        xs: { span: 24 },
        sm: { span: 13 }
      },
      formData: {
        //form表单数据
        imgUrl: null, //广告图片地址
        editId: null, //编辑id
        url: null//广告地址
      },
      activeOptions: [], //活动链接
      delData: [], //删除参数
      loadData: [], //列表数据
      title: '创建', //模态框标题
      loading: true,
      advanced: false,
      visible: false, //新建/编辑模态框
      delvisible: false, //删除模态框
      form: this.$form.createForm(this) //实例化form表单
    }
  },
  created() {
    this.getList() //获取列表
    this.getCategoryTree() //获取类目
  },
  methods: {
    getList() {
      //获取列表
      this.loading = true
      getAdlist(Object.assign(this.parameter)).then(res => {
        this.loadData = res.data.items
        this.loading = false
        this.pagination.total = res.data.total
      })
    },
    search() {
      //查询
      this.parameter.status = this.queryParam.status
      if (this.queryParam.status == 2) {
        this.parameter.status = undefined
      }
      this.getList()
    },
    pageChange(pagination) {
      //分页
      this.parameter.pageNo = pagination.current //点击的页码
      this.parameter.pageSize = pagination.pageSize //一页显示多少条
      this.getList()
    },
    adDelete() {
      //删除
      this.delvisible = false
      this.queryParam.adId = this.delData.id
      this.queryParam.adType = this.delData.adType
      deleteAdvertisement(Object.assign(this.queryParam)).then(res => {
        this.$notification.open({
          message: '成功',
          description: '删除成功',
          icon: <a-icon type="check-circle" style="color: #52c41a" />
        })
        this.getList()
      })
    },
    adEdit(row) {
      //编辑回显
      console.log(row);
      this.visible = true
      this.title = '编辑'
      this.formData.imgUrl = row.imgUrl //图片回显
      this.formData.editId = row.id // 编辑id
      let urlArr = row.url.split('=')
      this.formData.url = Number(urlArr[1]) //活动链接回显
      setTimeout(() => {
        //延时处理，避免出现渲染之前回显数据报错
        this.form.setFieldsValue({
          //设置回显参数
          title: row.title,
          imgUrl: row.imgUrl,
          adType: row.adType,
          status: row.status
        })
      }, 0)
    },
    newBulid() {
      //新建
      this.title = '创建'
      this.closeModal() //清空form表单项
      this.visible = true
      // this.activeOptions = null //清空类目
      this.getCategoryTree() //初始化类目
    },
    submit() {
      //提交
      let that = this
      that.form.validateFields((err, values) => {
        //获取form表单项
        if (!err) {
          values.imgUrl = that.formData.imgUrl //图片地址
          values.color = 'rgb(237,216,111)'
          values.adId = that.formData.editId //编辑提交id
          if (that.title == '创建') {
            //类目参数不在form中需要单独判断
            if (that.formData.url) {
              values.url = '/pages/product/detail?id=' + that.formData.url //活动链接
              that.formData = values
              // 新建提交
              that.visible = false
              buildSubmit(Object.assign(that.formData)).then(res => {
                that.closeModal() 
                that.$notification.open({
                  message: '成功',
                  description: '商铺广告创建成功',
                  icon: <a-icon type="check-circle" style="color: #52c41a" />
                })
                that.getList()
              })
            } else {
              that.$notification.open({
                message: '错误',
                description: '活动链接不能为空！',
                icon: <a-icon type="close-circle" style="color: red" />
              })
            }
          } else {
            //编辑提交
            editSubmit(Object.assign(that.formData)).then(res => {
              that.closeModal() //编辑成功关闭模态框清空form表单
              that.$notification.open({
                message: '成功',
                description: '修改成功',
                icon: <a-icon type="check-circle" style="color: #52c41a" />
              })
              that.getList()
            })
          }
        }
      })
    },
    closeModal() {
      //关闭模态框清空form内容
      this.visible = false
      this.form.resetFields()
      this.formData.imgUrl = null;
      this.formData.url = null;
    },
    imgUpload(info) {
      //图片上传
      let that = this
      that.formData.imgUrl = null
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        this.loading = false
        getBase64(info.file.originFileObj, imageUrl => {
          info.fileList.forEach(function(ele, index, arr) {
            that.formData.imgUrl = ele.response.url
          })
        })
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    },
    getCategoryTree() {
      //获取类目
      getCategoryTree(Object.assign(this.parameter)).then(res => {
        this.activeOptions = this.getTreeData(res.data)
      })
    },
    cascderchange(value) {
      //级联选择获取树状结构id
      this.formData.url = value[value.length-1]
    },
    getTreeData(data) {
      // 循环遍历json数据
      for (var i = 0; i < data.length; i++) {
        if (data[i].children == '' || data[i].children == undefined || data[i].children == null) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children)
        }
      }
      return data
    }
  }
}
</script>
<style scoped>
.flyray-btn {
  font-size: 12px;
  padding: 0 7px;
  margin: 0 0 0 3px;
  height: 24px;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.ant-upload.ant-upload-select-picture-card {
  background-color: #fff;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.ant-upload.ant-upload-select-picture-card > .ant-upload img {
  width: 145px;
  height: 145px;
}
.table-danger,
.table-danger:focus {
  color: #fff;
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  margin-left: 5px;
}
</style>
